package com.glory.wxelectricitypda.activity;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.LotBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.glory.wxelectricitypda.bean.PositionSetLineListBean;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MaterielReservationActivity extends BaseDialogActivity {

    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.flType)
    FrameLayout flType;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.ivType)
    ImageView ivType;
    @BindView(R.id.llmNoReturn)
    LinearLayout llmNoReturn;
    @BindView(R.id.flNoReturn)
    FrameLayout flNoReturn;
    @BindView(R.id.tvNoReturn)
    TextView tvNoReturn;
    @BindView(R.id.ivNoReturne)
    ImageView ivNoReturne;
    @BindView(R.id.flCode)
    FrameLayout flCode;
    @BindView(R.id.tvCode)
    TextView tvCode;
    @BindView(R.id.ivCode)
    ImageView ivCode;
    @BindView(R.id.flMaterierType)
    FrameLayout flMaterierType;
    @BindView(R.id.tvMaterierType)
    TextView tvMaterierType;
    @BindView(R.id.ivMaterierType)
    ImageView ivMaterierType;
    @BindView(R.id.flStepName)
    FrameLayout flStepName;
    @BindView(R.id.tvStepName)
    TextView tvStepName;
    @BindView(R.id.ivStepName)
    ImageView ivStepName;
    @BindView(R.id.flPositionSetLine)
    FrameLayout flPositionSetLine;
    @BindView(R.id.tvPositionSetLine)
    TextView tvPositionSetLine;
    @BindView(R.id.ivPositionSetLine)
    ImageView ivPositionSetLine;
    @BindView(R.id.tvPartName)
    TextView tvPartName;
    @BindView(R.id.rbMaterial)
    RadioButton rbMaterial;
    @BindView(R.id.tvUomId)
    TextView tvUomId;
    @BindView(R.id.tvApplyOutQty)
    TextView tvApplyOutQty;
    @BindView(R.id.etReceivedQuantity)
    FreeUI_ClearEditText etReceivedQuantity;
    @BindView(R.id.etTQuantity)
    FreeUI_ClearEditText etTQuantity;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.etNoReturn)
    FreeUI_ClearEditText etNoReturn;

    private FreeUI_GeneralPop mTypePop;
    private FreeUI_GeneralPop mCodePop;
    private FreeUI_GeneralPop mMaterierTypePop;
    private FreeUI_GeneralPop mStepNamePop;
    private FreeUI_GeneralPop mPositionSetLinePop;
    private FreeUI_GeneralPop mNoReturnePop;
    private ArrayList<String> typeList = new ArrayList<>();
    private ArrayList<String> typeIDList = new ArrayList<>();
    private ArrayList<String> nameList = new ArrayList<>();
    private ArrayList<String> codeList = new ArrayList<>();
    private ArrayList<String> materierTypeList = new ArrayList<>();
    private ArrayList<String> materierNameList = new ArrayList<>();
    private ArrayList<String> stepNameList = new ArrayList<>();
    private ArrayList<String> positionSetLineList = new ArrayList<>();
    private List<LotBean.MatTypeBean> matlist;
    private PopupWindow pop;
    StringBuffer num;
    private boolean isQu = true;

    private String orderQty = "0";
    private ArrayList<String> numList = new ArrayList<>();
    private Map<String, String> numMap = new HashMap<>();
    private ArrayList<String> noReturnList = new ArrayList<>();
    private Map<String, String> noReturnMap = new HashMap<>();
    private Double keyid;

    private Map<String, String> positionSetLineMap = new HashMap<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_materiel_reservation;
    }

    @Override
    protected void initView() {

    }

    private void getNumList() {
        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "GETBYREFNAME");
            map.put("REFNAME", "EUIT_MAT_USE_QTY_LEAD_FRAME");
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.EuitADUREFLISTHANDLER");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.AdurefBean adurefBean : response.body().getBody().getADUREFLIST()) {
                        numList.add(adurefBean.getTEXT());
                        numMap.put(adurefBean.getTEXT(), adurefBean.getKEYID());
                    }

                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ADUREFLISTHANDLER");
            }
        });

    }


    private void reasonsForNoReturn() {

        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "GETBYREFNAME");
            map.put("REFNAME", "EUIT_NOT_LT_REASON");
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.EuitADUREFLISTHANDLER");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.AdurefBean adurefBean : response.body().getBody().getADUREFLIST()) {
                        noReturnList.add(adurefBean.getTEXT());
                        noReturnMap.put(adurefBean.getTEXT(), adurefBean.getKEYID());
                    }

                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ADUREFLISTHANDLER");
            }
        });

    }


    @Override
    protected void initData() {
//        typeList.add("以旧换新，旧的报废");
//        typeList.add("不报废，归还");
        getScrapcodeList();
        getNumList();
        reasonsForNoReturn();

        //扫描触发
        initEdit(etLotId, s -> {
            JSONObject jsonObject = new JSONObject();
            JSONObject jsonObject1 = new JSONObject();
            try {
                jsonObject1.put("LOTID", s);
                jsonObject1.put("ACTIONTYPE", "GETLOTINFO");
                jsonObject.put("Data", jsonObject1);
                jsonObject.put("MessageName", "EUIT.EUITLOTQUERY");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                    new TypeToken<ResponseBean<LotBean>>() {
                    }.getType(), getSupportFragmentManager(), this) {
                @Override
                public void onSuccess(Response<ResponseBean<LotBean>> response) {
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {


                        String reserved1 = response.body().getBody().getLOT().getUDF().getRESERVED1();
                        boolean tvNum = false;
                        for (String num : numList) {
                            if (num.equals(reserved1)) {
                                tvNum = true;
                                break;
                            }
                        }

                        if (tvNum) {
                            try {
                                keyid = Double.parseDouble(numMap.get(reserved1));
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                                keyid = -1.0;
                            }
                        } else {
                            keyid = -1.0;
                        }

                        tvPartName.setText(response.body().getBody().getLOT().getPARTNAME());
                        tvStepName.setText(response.body().getBody().getLOT().getSTEPNAME());
                        orderQty = response.body().getBody().getWORKORDER().getMAIN_QTY();


                    }
                }

                @Override
                public void onError(Response<ResponseBean<LotBean>> response) {
                    super.onError(response);
                    loadError(response.getException(), "GETLOTINFO");
                }
            });
        });
        getMlotAppLycreate();

        freeUI_titleView.setRightListener("预约", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etLotId.getText().toString().equals("")) {
                    showToast("请扫描批次号", false);
                    return;
                }
                if (tvStepName.getText().toString().equals("")) {
                    showToast("请选择工序", false);
                    return;
                }
                if (etEqpId.getText().toString().equals("")) {
                    showToast("请扫描设备", false);
                    return;
                }
                if (tvPositionSetLine.getText().toString().equals("")) {
                    showToast("请选择上料口", false);
                    return;
                }
                if (tvMaterierType.getText().toString().equals("")) {
                    showToast("请选择物料类型", false);
                    return;
                }
                if (tvCode.getText().toString().equals("")) {
                    showToast("请选择物料编码", false);
                    return;
                }
                if (tvType.getText().toString().equals("")) {
                    showToast("请选择领用类型", false);
                    return;
                }
                if (etTQuantity.getText().toString().equals("")) {
                    showToast("请输入实际领用数量", false);
                    return;
                }
                if (llmNoReturn.getVisibility() == View.VISIBLE) {
                    if (etNoReturn.getText().toString().isEmpty()) {
                        showToast("请输入未能归还原因", false);
                        return;
                    }
                }


                num = new StringBuffer();

                if (tvMaterierType.getText().toString().contains("框架")) {

                    View bottomView = View.inflate(MaterielReservationActivity.this, R.layout.dialog_materielreservation, null);
                    TextView endNum = bottomView.findViewById(R.id.endNum);
                    FreeUI_ClearEditText nowNum = bottomView.findViewById(R.id.nowNum);
                    Button ok = bottomView.findViewById(R.id.ok);
                    Button no = bottomView.findViewById(R.id.no);

                    pop = new PopupWindow(bottomView, -2, -2);
                    pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    pop.setOutsideTouchable(false);
                    pop.setFocusable(true);
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = 0.5f;
                    getWindow().setAttributes(lp);
                    pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

                        @Override
                        public void onDismiss() {
                            WindowManager.LayoutParams lp = getWindow().getAttributes();
                            lp.alpha = 1f;
                            getWindow().setAttributes(lp);
                        }
                    });
                    pop.setAnimationStyle(R.style.main_menu_photo_anim);
                    pop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);

                    nowNum.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void afterTextChanged(Editable editable) {
                            endNum.setText(String.valueOf(Double.parseDouble(etTQuantity.getText().toString()) - (double) (Double.parseDouble(tvApplyOutQty.getText().toString()) * Integer.parseInt(editable.toString()))));
                        }
                    });

                    ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            num.setLength(0);
                            num.append(endNum.getText().toString());
                            closePopupWindow();
                            submit();
                        }
                    });

                    no.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            closePopupWindow();
                        }
                    });

                } else {
                    submit();
                }

            }
        });
        etReceivedQuantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isQu = true;
            }
        });
        etReceivedQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString() != null && isQu) {
                    if (!s.toString().isEmpty() && !tvApplyOutQty.getText().toString().isEmpty()) {
                        String s1 = s.toString();
                        if (s1.equals(".")) {
                            s1 = "0."; // 将仅包含小数点的情况转换为合法的小数格式
                        }
                        BigDecimal bd1 = new BigDecimal(s1.trim());
                        BigDecimal bd2 = new BigDecimal(tvApplyOutQty.getText().toString().trim());
                        double v2 = bd1.multiply(bd2).doubleValue();
                        etTQuantity.setText(String.valueOf(v2));
                    }
                }

            }
        });
        etTQuantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isQu = false;
            }
        });
        initEdit(etEqpId, s -> {
            materierTypeList.clear();
            codeList.clear();
            tvMaterierType.setText("");
            tvCode.setText("");
            queryMaterierType();
        });
    }

    private void getScrapcodeList() {
        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "GETBYREFNAME");
            map.put("REFNAME", "SBE_MLOT_APPOINTMENT_MA_TYPE");
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.EuitADUREFLISTHANDLER");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.AdurefBean adurefBean : response.body().getBody().getADUREFLIST()) {
                        typeIDList.add(adurefBean.getKEYID());
                        typeList.add(adurefBean.getTEXT());
                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ADUREFLISTHANDLER");
            }
        });

    }


    private void getMlotAppLycreate() {
        stepNameList.clear();
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "ACTIVESTEP");
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.StepBean stepBean : response.body().getBody().getSTEPLIST()) {
                        stepNameList.add(stepBean.getNAME());
                    }
                } else {
                    finish();
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ACTIVESTEP");
                finish();
            }
        });
    }


    private void queryEqp() {
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "QUERYEQP");
            jsonObject1.put("LOTID", etLotId.getText().toString());
            jsonObject1.put("STEPNAME", tvStepName.getText().toString());
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "QUERYEQP");
            }
        });
    }

    private void queryMaterierType() {
        materierTypeList.clear();
        materierNameList.clear();
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "QUERYMATTYPE");
            jsonObject1.put("LOTID", etLotId.getText().toString());
            jsonObject1.put("STEPNAME", tvStepName.getText().toString());
            jsonObject1.put("EQUIPMENTID", etEqpId.getText().toString());
            jsonObject1.put("CLAZZ", rbMaterial.isChecked() ? "MAT" : "TOOL");
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.MatTypeBean matTypeBean : response.body().getBody().getMATTYPELIST()) {
                        materierNameList.add(matTypeBean.getNAME());
                        materierTypeList.add(matTypeBean.getDESCRIPTION());
                    }
                    if (materierTypeList.size() > 0) {
                        tvMaterierType.setText(materierTypeList.get(0));
                    }
                    queryMatCode();
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "QUERYMATTYPE");
            }
        });
    }

    private void queryMatCode() {
        codeList.clear();
        nameList.clear();
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "QUERYMAT");
            jsonObject1.put("LOTID", etLotId.getText().toString());
            jsonObject1.put("STEPNAME", tvStepName.getText().toString());
            jsonObject1.put("EQUIPMENTID", etEqpId.getText().toString());
            String name = tvMaterierType.getText().toString();
            for (int i = 0; i < materierTypeList.size(); i++) {
                if (tvMaterierType.getText().toString().equals(materierTypeList.get(i))) {
                    name = materierNameList.get(i);
                }
            }
            jsonObject1.put("MATTYPE", name);
            jsonObject1.put("CLAZZ", rbMaterial.isChecked() ? "MAT" : "TOOL");
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    matlist = response.body().getBody().getMATLIST();
                    for (LotBean.MatTypeBean matTypeBean : response.body().getBody().getMATLIST()) {
                        nameList.add(matTypeBean.getMATERIALNAME());
                        codeList.add(matTypeBean.getDESCRIPTION());
                    }
                    if (codeList.size() > 0) {
                        tvCode.setText(codeList.get(0));
                        queryApplyoutQTY();
                    }
                    for (int i = 0; i < codeList.size(); i++) {
                        if (codeList.get(0).equals(codeList.get(i))) {
                            for (LotBean.MatTypeBean matTypeBean : matlist) {
                                if (matTypeBean.getMATERIALNAME().equals(nameList.get(i))) {
                                    tvUomId.setText(matTypeBean.getUomId());
                                    if (matTypeBean.getUdf() != null) {
                                        tvApplyOutQty.setText(matTypeBean.getUdf().getApplyOutQty());
                                    }
                                    if (tvMaterierType.getText().toString().equals("Lead_Frame") || tvMaterierType.getText().toString().equals("引线框架")) {


                                        double result = (Double.parseDouble(orderQty)) / 1000.00 * 1.02; // 工单数量*1.02/最小包装数
                                        DecimalFormat decimalFormat = new DecimalFormat("#.#####"); // 设置格式化规则
                                        String formattedResult = "";
                                        if (matTypeBean.getUdf() != null) {
                                            if (matTypeBean.getUdf().getApplyOutQty().isEmpty()) {
                                                showToast(etLotId.getText().toString() + "没有维护单位用量!", false);
                                                etReceivedQuantity.setText("");
                                            } else {
                                                formattedResult = decimalFormat.format(result / Double.valueOf(matTypeBean.getUdf().getApplyOutQty())); // 格式化结果
                                                int roundedResult = (int) Math.ceil(Double.parseDouble(formattedResult)); // 向上取整

                                                if (keyid != -1.0) {
                                                    String applyOutQty = matTypeBean.getUdf().getApplyOutQty();     //标准用量，每盒量25
                                                    Log.d("aaaaaa", applyOutQty);
                                                    Log.d("aaaaaa", String.valueOf(keyid));
                                                    double v = Double.parseDouble(applyOutQty);
                                                    int i1 = (int) Math.ceil(keyid / v);
                                                    if (i1 < roundedResult) {
                                                        etReceivedQuantity.setText(String.valueOf(i1));
                                                    } else {
                                                        etReceivedQuantity.setText(String.valueOf(roundedResult));
                                                    }

                                                } else {
                                                    etReceivedQuantity.setText(String.valueOf(roundedResult));

                                                }

                                            }
                                        } else {
                                            etReceivedQuantity.setText("");
                                        }
                                    }

                                } else {
                                    etReceivedQuantity.setText("");
                                }

                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "QUERYMAT");
            }
        });


        String epid = etEqpId.getText().toString();
        if(null != epid && !epid.isEmpty()){
            positionSetLineList.clear();
            positionSetLineMap.clear();
            tvPositionSetLine.setText("");
            //选择设备后调查询上料口位置方法
            queryPositionSetLine();
        }
    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("治具物料预约");
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.flType, R.id.flCode, R.id.flMaterierType, R.id.flStepName, R.id.flPositionSetLine, R.id.flNoReturn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flType:
                if (mTypePop != null) {
                    if (mTypePop.isShowing()) {
                        mTypePop.dismiss();
                    }
                } else {
                    mTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flType.getWidth(), typeList, ivType, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvType.setText(s);
                            for (int i = 0; i < typeList.size(); i++) {
                                if (s.equals(typeList.get(i))) {
                                    Log.d("aaa", typeIDList.get(i));
                                    if (typeIDList.get(i).equals("L")) {
                                        llmNoReturn.setVisibility(View.VISIBLE);
                                    } else {
                                        llmNoReturn.setVisibility(View.GONE);
                                        etNoReturn.setText("");
                                    }
                                }
                            }

                        }
                    });
                }

                FreeApi_PopUtils.setArrowShow(ivType);
                mTypePop.showAsDropDown(flType, 0, 0);
                break;
            case R.id.flCode:
                if (mCodePop != null) {
                    if (mCodePop.isShowing()) {
                        mCodePop.dismiss();
                    }
                } else {
                    mCodePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCode.getWidth(), codeList, ivCode, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvCode.setText(s);
                            queryApplyoutQTY();
                            for (int i = 0; i < codeList.size(); i++) {
                                if (s.equals(codeList.get(i))) {
                                    for (LotBean.MatTypeBean matTypeBean : matlist) {
                                        if (matTypeBean.getMATERIALNAME().equals(nameList.get(i))) {
                                            tvUomId.setText(matTypeBean.getUomId());
                                            if (matTypeBean.getUdf() != null) {
                                                tvApplyOutQty.setText(matTypeBean.getUdf().getApplyOutQty());
                                            }
                                            if (tvMaterierType.getText().toString().equals("Lead_Frame") || tvMaterierType.getText().toString().equals("引线框架")) {
                                                double result = (Double.parseDouble(orderQty)) / 1000.00 * 1.02; // 工单数量*1.02/最小包装数
                                                DecimalFormat decimalFormat = new DecimalFormat("#.#####"); // 设置格式化规则
                                                String formattedResult = "";
                                                if (matTypeBean.getUdf() != null) {
                                                    if (matTypeBean.getUdf().getApplyOutQty().isEmpty()) {
                                                        showToast(etLotId.getText().toString() + "没有维护单位用量!", false);
                                                        etReceivedQuantity.setText("");
                                                    } else {
                                                        formattedResult = decimalFormat.format(result / Double.valueOf(matTypeBean.getUdf().getApplyOutQty())); // 格式化结果
                                                        int roundedResult = (int) Math.ceil(Double.parseDouble(formattedResult)); // 向上取整

                                                        if (keyid != -1.0) {
                                                            String applyOutQty = matTypeBean.getUdf().getApplyOutQty();     //标准用量，每盒量25
                                                            Log.d("aaaaaa", applyOutQty);
                                                            Log.d("aaaaaa", String.valueOf(keyid));
                                                            double v = Double.parseDouble(applyOutQty);
                                                            int i1 = (int) Math.ceil(keyid / v);
                                                            if (i1 < roundedResult) {
                                                                etReceivedQuantity.setText(String.valueOf(i1));
                                                            } else {
                                                                etReceivedQuantity.setText(String.valueOf(roundedResult));
                                                            }

                                                        } else {
                                                            etReceivedQuantity.setText(String.valueOf(roundedResult));

                                                        }

                                                    }
                                                } else {
                                                    etReceivedQuantity.setText("");
                                                }
                                            }
                                        } else {
                                            etReceivedQuantity.setText("");
                                        }


//                                        }
                                    }
                                }
                            }

                        }
                    });
                }

                FreeApi_PopUtils.setArrowShow(ivCode);
                mCodePop.showAsDropDown(flCode, 0, 0);
                break;
            case R.id.flMaterierType:
                if (mMaterierTypePop != null) {
                    if (mMaterierTypePop.isShowing()) {
                        mMaterierTypePop.dismiss();
                    }
                } else {
                    mMaterierTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flMaterierType.getWidth(), materierTypeList, ivMaterierType, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvMaterierType.setText(s);
                            tvCode.setText("");
                            codeList.clear();
                            queryMatCode();
                        }
                    });
                }

                FreeApi_PopUtils.setArrowShow(ivMaterierType);
                mMaterierTypePop.showAsDropDown(flMaterierType, 0, 0);
                break;
            case R.id.flStepName:
                if (mStepNamePop != null) {
                    if (mStepNamePop.isShowing()) {
                        mStepNamePop.dismiss();
                    }
                } else {
                    mStepNamePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStepName.getWidth(), stepNameList, ivStepName, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            if (etLotId.getText().toString().equals("")) {
                                showToast("请先扫描批次", false);
                                tvStepName.setText("");
                                return;
                            }
                            materierTypeList.clear();
                            codeList.clear();
                            tvStepName.setText(s);
                            tvMaterierType.setText("");
                            tvCode.setText("");
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivStepName);
                mStepNamePop.showAsDropDown(flStepName, 0, 0);
                break;
            case R.id.flPositionSetLine:
                mPositionSetLinePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionSetLine.getWidth(), positionSetLineList, ivPositionSetLine, new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        tvPositionSetLine.setText(s);
                    }
                });
                FreeApi_PopUtils.setArrowShow(ivPositionSetLine);
                mPositionSetLinePop.showAsDropDown(flPositionSetLine, 0, 0);
                break;
            case R.id.flNoReturn:
                if (mNoReturnePop != null) {
                    if (mNoReturnePop.isShowing()) {
                        mNoReturnePop.dismiss();
                    }
                } else {
                    mNoReturnePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flNoReturn.getWidth(), noReturnList, ivNoReturne, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvNoReturn.setText(s);
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivNoReturne);
                mNoReturnePop.showAsDropDown(flNoReturn, 0, 0);
                break;
        }
    }

    private void queryApplyoutQTY() {

        if (rbMaterial.isChecked()) {
            return;
        }

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "QUERYMATDZAPPLYOUTQTY");
            String materialname = tvCode.getText().toString();
            for (int i = 0; i < codeList.size(); i++) {
                if (tvCode.getText().toString().equals(codeList.get(i))) {
                    materialname = nameList.get(i);
                }
            }
            jsonObject1.put("MATERIALNAME", materialname);
            String name = tvMaterierType.getText().toString();
            for (int i = 0; i < materierTypeList.size(); i++) {
                if (tvMaterierType.getText().toString().equals(materierTypeList.get(i))) {
                    name = materierNameList.get(i);
                }
            }
            jsonObject1.put("MATTYPE", name);
            jsonObject1.put("LOTID", etLotId.getText().toString());
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    if (response.body().getBody().getAPPLYOUTQTY().isEmpty()) {
                        etTQuantity.setText("");
                        etReceivedQuantity.setEnabled(true);
                        etTQuantity.setEnabled(true);
                    } else {
                        etTQuantity.setText(response.body().getBody().getAPPLYOUTQTY());
                        etReceivedQuantity.setEnabled(false);
                        etTQuantity.setEnabled(false);
                    }

                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ACTIVESTEP");
            }
        });


    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }


    private void submit() {

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        try {
            jsonObject2.put("ACTIONTYPE", "A");
            jsonObject1.put("LOTID", etLotId.getText().toString());
            jsonObject1.put("STEPNAME", tvStepName.getText().toString());
            jsonObject1.put("LTREASON", etNoReturn.getText().toString());
            jsonObject1.put("EQUIPMENTID", etEqpId.getText().toString());
            String name = tvMaterierType.getText().toString();
            for (int i = 0; i < materierTypeList.size(); i++) {
                if (tvMaterierType.getText().toString().equals(materierTypeList.get(i))) {
                    name = materierNameList.get(i);
                }
            }
            jsonObject1.put("MATTYPE", name);
            String typeName = tvType.getText().toString();
            for (int i = 0; i < typeList.size(); i++) {
                if (tvType.getText().toString().equals(typeList.get(i))) {
                    typeName = typeIDList.get(i);
                }
            }
            jsonObject1.put("MATYPE", typeName);
            jsonObject1.put("EQPLOCATION", positionSetLineMap.get(tvPositionSetLine.getText().toString()));
            jsonObject1.put("CLASS", rbMaterial.isChecked() ? "MAT" : "TOOL");
            jsonObject1.put("MAINQTY", etReceivedQuantity.getText().toString());
            jsonObject1.put("MLOTMAINQTY", num.toString().isEmpty() ? etTQuantity.getText().toString() : num.toString());
            String materialname = tvCode.getText().toString();
            for (int i = 0; i < codeList.size(); i++) {
                if (tvCode.getText().toString().equals(codeList.get(i))) {
                    materialname = nameList.get(i);
                }
            }
            jsonObject1.put("MATERIALNAME", materialname);
            jsonObject2.put("MLOTAPPOINTMENT", jsonObject1);
            jsonObject.put("Data", jsonObject2);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            showToast("预约成功", true);
//                            finish();
//                        }
//                    }, 2000);

                    showToast("预约成功，预约单号：" + response.body().getBody().getMAID(), true);
                    finish();
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "A");
            }
        });
    }


    private void queryPositionSetLine() {
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject mlotAppointment = new JSONObject();
        try {
            mlotAppointment.put("EQUIPMENTID", etEqpId.getText().toString());
            jsonObject1.put("ACTIONTYPE", "QUERYEQPLOCATION");
            jsonObject1.put("MLOTAPPOINTMENT", mlotAppointment);
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<PositionSetLineListBean>>(
                new TypeToken<ResponseBean<PositionSetLineListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<ResponseBean<PositionSetLineListBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<PositionSetLineListBean.PositionSetLineBean> positionList = response.body().getBody().getPOSITIONSETLINELIST();
                    if (null != positionList && positionList.size() > 0) {
                        for (PositionSetLineListBean.PositionSetLineBean positionSetLineBean : positionList) {
                            positionSetLineList.add(positionSetLineBean.getPOSITIONDESC());
                            positionSetLineMap.put(positionSetLineBean.getPOSITIONDESC(), positionSetLineBean.getPOSITIONNAME());
                        }
                    }else{
                        positionSetLineList.clear();
                        positionSetLineMap.clear();
                        tvPositionSetLine.setText("");
                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<PositionSetLineListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYCREATE");
            }

        });
    }


}

